import {useEffect, useState} from "react";
import {treeMenu} from "@/pages/system/menu/api";
import {message} from "antd";

// 定义返回的树形数据类型
interface MenuTreeHookResult {
  treeData: any[];
  originalTreeData: any[];
  getMenuTree: (searchName: string) => Promise<void>;
}

const mapTree = (item: any) => {
  if (!item) return item;
  const haveChildren = Array.isArray(item.children) && item.children.length > 0;
  const newItem = {
    title: item.name,
    key: item.id,
    icon: item.icon,
    children: haveChildren ? item.children.map((i: any) => mapTree(i)) : [],
  };
  if (newItem.children.length <= 0) {
    delete newItem.children;
  }
  return newItem;
};

export const useMenuTree = (): MenuTreeHookResult => {
  // 转化为树形结构之后的数据
  const [treeData, setTreeData] = useState<any[]>([]);
  const [originalTreeData, setOriginalTreeData] = useState<any[]>([]);

  const getMenuTree = async (searchName: string) => {
    try {
      const {data} = await treeMenu(searchName, 0);
      setTreeData(data.map((item: any) => mapTree(item)));
      setOriginalTreeData(data);
    } catch (e: any) {
      message.error(e);
    }
  };

  useEffect(() => {
    getMenuTree(""); // 组件挂载时默认加载
  }, []);

  return {treeData, getMenuTree, originalTreeData};
};
